package top.mingyi4cjh.cms.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.mingyi4cjh.cms.common.configuration.AccessLimit;
import top.mingyi4cjh.cms.common.error.BusinessException;
import top.mingyi4cjh.cms.common.error.EmBusinessError;
import top.mingyi4cjh.cms.common.response.CommonReturnType;
import top.mingyi4cjh.cms.common.utils.CosUtil;
import top.mingyi4cjh.cms.common.utils.UserInfoUtils;
import top.mingyi4cjh.cms.model.FileModel;
import top.mingyi4cjh.cms.service.FileService;
import top.mingyi4cjh.cms.viewobject.FileVO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static top.mingyi4cjh.cms.common.utils.UuidManager.UUID_MANAGER;

/**
 * @author MingYi
 * @program cms
 * @create 2022/04/26 23:58
 */
@Api
@RestController("file")
@RequestMapping(value = "/file", method = {RequestMethod.GET, RequestMethod.POST})
public class FileController extends BaseController {

    @Resource
    private FileService fileService;

    @Resource
    private HttpServletRequest request;

    @Resource
    private UserInfoUtils userInfoUtils;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件id
     */
    @ApiOperation(value = "上传文件")
    @AccessLimit
    @PostMapping(value = "/upload", consumes = {CONTENT_TYPE_DATA})
    public CommonReturnType uploadFile(MultipartFile file) {
        //验证用户是否登录，不是就抛出未登录异常
        String userId = userInfoUtils.getLoginUserId(request);
        //判断文件是否有内容，没有则抛出无效文件异常
        if (file == null || file.isEmpty()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }

        //生成文件id
        Long fileId = UUID_MANAGER.getUuid();

        //调用service层的uploadFile方法
        fileService.uploadFile(fileId, file, Long.valueOf(userId));
        return CommonReturnType.create(fileId);
    }

    /**
     * 下载文件
     *
     * @param fileStr 字符串形式的文件id
     * @return null
     */
    @ApiOperation(value = "获取文件临时下载链接")
    @AccessLimit
    @PostMapping(value = "/download", consumes = {CONTENT_TYPE_FORMED})
    public CommonReturnType downloadFile(@RequestParam(name = "fileId") String fileStr) {
        //验证用户是否登录
        String userId = userInfoUtils.getLoginUserId(request);
        Long fileId = Long.valueOf(fileStr);

        //验证是否是该用户的文件，不是则抛出FILE_OWNER_FAIL
        if (!fileService.isFileOwner(Long.valueOf(userId), fileId)) {
            throw new BusinessException(EmBusinessError.FILE_OWNER_FAIL, "没有权限下载该文件");
        }
        //调用service层的downloadFile方法
        String downFile = fileService.downFile(fileId);

        // 生成临时链接
        // 填写本次请求的参数
        Map<String, String> params = new HashMap<>(16);
        params.put("userId", userId);
        String url = CosUtil.getObjectTemporaryUrl(downFile, params, "POST", userInfoUtils.getToken(request));
        return CommonReturnType.create(downFile);
    }

    @ApiOperation(value = "删除文件")
    @AccessLimit
    @PostMapping(value = "/delete", consumes = {CONTENT_TYPE_FORMED})
    public CommonReturnType deleteFile(@RequestParam(name = "fileId") String fileStr) {
        //验证用户是否登录
        String userId = userInfoUtils.getLoginUserId(request);
        Long fileId = Long.valueOf(fileStr);

        //验证是否是该用户的文件，不是则抛出FILE_OWNER_FAIL
        if (!fileService.isFileOwner(Long.valueOf(userId), fileId)) {
            throw new BusinessException(EmBusinessError.FILE_OWNER_FAIL, "没有权限下载该文件");
        }
        //调用service层的deleteFile方法
        fileService.deleteFile(fileId);

        return CommonReturnType.create(null);
    }

    @ApiOperation(value = "获取文件列表")
    @AccessLimit
    @GetMapping(value = "/getFileList")
    public CommonReturnType getFileList() {
        String userId = userInfoUtils.getLoginUserId(request);
        //调用service层的接口获取Model列表
        List<FileModel> fileModels = new ArrayList<>();
        fileModels = fileService.getFileList(Long.valueOf(userId));
        //将Model列表转换为VO列表，可以参考之前写的转换，需要一个convert方法，然后可以用stream的map方法写个lambda表达式
        FileVO fileVO = convertFromModel(fileModels);
        //返回转换结果
        return CommonReturnType.create(fileVO);
    }

    private FileVO convertFromModel(List<FileModel> fileModels) {
        if (fileModels == null) {
            return null;
        }
        FileVO fileVO = new FileVO();
        BeanUtils.copyProperties(fileModels, fileVO);
        return fileVO;
    }

    @ApiOperation(value = "预览文件")
    @AccessLimit
    @PostMapping(value = "/preview", consumes = {CONTENT_TYPE_FORMED})
    public CommonReturnType previewFile(String fileId) {
        //技术方面还没有完全搞定，搞定后开放该接口
        return CommonReturnType.create("该接口未开放");

//        //校验用户是否登录
//        Long userId = (Long) request.getSession().getAttribute(LOGIN_USER);
//        if (userId == null) {
//            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"您还未登录");
//        }
//
//        //校验文件是否是该用户的文件
//        if (!fileService.isFileOwner(userId, Long.valueOf(fileId))) {
//            throw new BusinessException(EmBusinessError.FILE_OWNER_FAIL, "这不是您的文件");
//        }
//        //调用service层的preview方法
//
//        String filePath = fileService.previewFilePath(Long.valueOf(fileId));
//        if (filePath != null) {
//            //获取文件和pdf绝对路径
//            Map<String, String> map = FileToPdfComUtils.filepathToPdfPath(filePath);
//            String pdfPath = map.get("pdfPath");
//
//            //如果文件不存在则生成pdf
//            File file = new File(pdfPath);
//            if (!file.exists()) {
//                officeToPdf(filePath);
//            }
//            try {
//                FileCopyUtils.copy(new FileInputStream(pdfPath), response.getOutputStream());
//            } catch (IOException e) {
//                throw new BusinessException(EmBusinessError.FILE_PREVIEW_FAIL);
//            }
//        }else{
//            throw new BusinessException(EmBusinessError.FILE_CAN_NOT_PREVIEW);
//        }
//
//        return CommonReturnType.create(null);
    }


}
